package com.lujianfei.babymilkmemory

import android.os.Bundle
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.*
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.unit.ExperimentalUnitApi
import androidx.lifecycle.ViewModelProvider
import com.lujianfei.babymilkmemory.compose.MainCompose
import com.lujianfei.babymilkmemory.compose.MainComposeType
import com.lujianfei.babymilkmemory.sp.Setting
import com.lujianfei.babymilkmemory.viewmodel.MainViewModel

class MainActivity : ComponentActivity() {

    private var mainViewModel: MainViewModel? = null

    @ExperimentalComposeUiApi
    @ExperimentalUnitApi
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainViewModel = ViewModelProvider(this)[MainViewModel::class.java]
        mainViewModel?.let {
            setContent {
                content()
            }
        }
    }

    override fun onResume() {
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        super.onResume()
    }

    override fun onPause() {
        window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        super.onPause()
    }

    override fun onDestroy() {
        mainViewModel?.stopTimer()
        super.onDestroy()
    }

    @ExperimentalComposeUiApi
    @ExperimentalUnitApi
    @Composable
    fun content() {
        if (mainViewModel == null) return
        val navController = remember { mutableStateOf(MainComposeType.fromLabel(Setting.INSTANCE.lastOperationLabel)) }
        MainCompose(mainViewModel = mainViewModel!!, navController = navController)
        mainViewModel?.startTimer(navController.value)
    }
}